// ==UserScript==
// @name        Gifyo Notifier
// @namespace   https://www.gifyo.com/
// @description Notifier for Gifyo - released under Apache 2.0 Licence by LazyScripter
// @downloadURL http://lazyscripter.tumblr.com
// @icon 	http://i.imgur.com/xW43M5q.png
// @include     https://*gifyo.com/dashboard*
// @include     http://*gifyo.com/dashboard*
// @version     v1.0
// @grant       none
// ==/UserScript==
var minutesCountdown = 1; //Minutes in which notifications are checked, you can change it for values>1. Default value is set to 1
var gifyoNotifier = function()
{
	console.log("Gifyo Notifier: started");
	function sendRequest(){
		var xmlReq = new XMLHttpRequest();
		xmlReq.open("GET", "http://gifyo.com/", true);
		xmlReq.onload=function(e){
			var httpText = xmlReq.responseText;
            //console.log(httpText);
            var toSearch = "/><span>";
			//var toSearch2 = "<span>";
			var notifications = "";
			for(var i=0;i<httpText.length;i++){
				if(httpText.substring(i,i+toSearch.length)==toSearch){				
					i=i+toSearch.length;
					/*hile(httpText.substring(i,i+toSearch2.length)!==toSearch2){
						i++;
					}
					i=i+toSearch2.length;*/
					while(httpText[i]!='<'){
				            notifications+=httpText[i];
				            i++;
				        }
					if(notifications=="0"||notifications=="")
						return;
					notifyMe(notifications);
					return;
				}
			}
		}
		xmlReq.send();
	}
	function notifyMe(notifications) {
	  if (!("Notification" in window)) {
	    alert("This browser does not support desktop notification");
	  }

	  else if (Notification.permission === "granted") {
	    var img = "http://i.imgur.com/xW43M5q.png";
        var text = "You have "+notifications+" notifications!";
		var notification = new Notification('Gifyo Notifications',{ body: text, icon: img });
	  }
	  else if (Notification.permission !== 'denied') {
	    Notification.requestPermission(function (permission) {

	      if(!('permission' in Notification)) {
		Notification.permission = permission;
	      }

	      if (permission === "granted") {
              var img = "http://i.imgur.com/xW43M5q.png";
              var text = "You have "+notifications+" notifications!";
		      var notification = new Notification('Tumblr Notifications',{ body: text, icon: img });
	      }
	    });
	  }

	}
	setInterval(sendRequest,minutesCountdown*60000);
}();
